namespace SS.WPF.Toolkit.PropertyEditor
{
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    public static class CellBinding
    {
        /// <summary>
        /// A dependency property for preventing closing 
        /// </summary>
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.RegisterAttached(
                "Text", typeof(string), typeof(CellBinding), new PropertyMetadata(OnTextChanged));

        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textBox = d as TextBox;
            if (textBox == null)
            {
                return;
            }

            var bindingGroupName = Framework.Markup.Control.GetBindingGroup(textBox);
            var binding = new Binding((string) e.NewValue)
                              {
                                  UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                                  Mode = BindingMode.TwoWay,
                                  ValidatesOnExceptions = true,
                                  ValidatesOnDataErrors = true,
                                  NotifyOnValidationError = true,
                                  BindingGroupName = bindingGroupName
                              };

            if (bindingGroupName != null)
            {
                Framework.Markup.Control.SetBindingGroup(textBox, bindingGroupName);
            }

            textBox.SetBinding(TextBox.TextProperty, binding);
        }

        /// <summary>
        /// Get Restriction property.
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        /// <returns>
        /// The moveable property value.
        /// </returns>
        public static string GetText(TextBox control)
        {
            return (string)control.GetValue(TextProperty);
        }

        /// <summary>
        /// Set IsEnabled property.
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public static void SetText(TextBox control, string value)
        {
            control.SetValue(TextProperty, value);
        }
    }
}